package com.smartystars.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import com.smartystars.quizzerServer.DownloadableQuestions;
import com.smartystars.quizzerServer.Question;

public class ClientHandler extends Thread {
	private Socket clientsocket;
	private ObjectInputStream in = null;
	private ObjectOutputStream out = null;

	public ClientHandler(Socket clientSocket) {
		this.clientsocket = clientSocket;

	}

	@Override
	public void run() {
		try {

			String message = leseNachricht(clientsocket);

			if (message.contains("Deutsch")) {
				System.out.println("Sende Deutsche Fragen");
				serveClient(Server.responseList_D);
			}else if (message.contains("REGISTER")){
				System.out.println("Register");
				String[] response = message.split("\\;");
				String name = response[1];
				String pw = response[2];
				String ID = response[3];
				
				String LoginString = "http://www.smartystars.de/quizzer/login/login.php?action=reg&nick="
						+name +"&pw=" + pw + "&geraeteid=" + ID;
				
				String ResponseString = getHTML(LoginString);
				schreibeNachricht(clientsocket, ResponseString);
				
			}else if(message.contains("LOGIN")){
				System.out.println("Login");
				
				String[] response = message.split("\\;");
				String name = response[1];
				String pw = response[2];
				
				String LoginString = "http://www.smartystars.de/quizzer/login/login.php?action=login&nick="
						+name +"&pw=" + pw ;
				String ResponseString = getHTML(LoginString);
				schreibeNachricht(clientsocket, ResponseString);
				
			}else if(message.contains("CHECKFORFRIEND")){
				System.out.println("CHECKFORFRIEND");
				String[] response = message.split("\\;");
				String name = response[1];
				String RequestString = "http://smartystars.de/quizzer/games/games.php?action=check&user="+name;
				String ResponseString = getHTML(RequestString);
				schreibeNachricht(clientsocket, ResponseString);
			}

		} catch (Exception e) {
			System.out.println(e);
			try {
				clientsocket.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		try {
			clientsocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void serveClient(ArrayList<Question> response) {

		try {
			// Socket s = new Socket(message.ID, 4090);
			out = new ObjectOutputStream(clientsocket.getOutputStream());
			DownloadableQuestions qresponse = new DownloadableQuestions(response);
			out.writeObject(qresponse);
			out.flush();
			out.close();
			clientsocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	String leseNachricht(java.net.Socket socket) throws IOException {
		try {
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(socket.getInputStream()));
			char[] buffer = new char[200];
			int anzahlZeichen = bufferedReader.read(buffer, 0, 200); // blockiert
																		// bis
																		// Nachricht
																		// empfangen
			if ((anzahlZeichen <= 200) && (anzahlZeichen >= 0)) {
				String nachricht = new String(buffer, 0, anzahlZeichen);
				return nachricht;
			} else {
				
				return null;
			}
		} catch (IOException e) {

			return null;
		}
	}
	
	void schreibeNachricht(java.net.Socket socket, String nachricht)
			throws IOException {
		PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(
				socket.getOutputStream()));
		printWriter.print(nachricht);
		printWriter.flush();
	}
	
	private static String getHTML(String urlToRead){
		URL url;
		HttpURLConnection conn;
		BufferedReader rd;
		String line;
		String result = "";
		
		try{
			url = new URL(urlToRead);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			while((line = rd.readLine()) != null){
				result+=line;
			}
			rd.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
}
